package cn.holy.app.xcddt.ui.activity.login.view

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import cn.holy.app.xcddt.domain.LoginFormBean
import cn.holy.app.xcddt.domain.UserBean
import cn.holy.app.xcddt.net.callback.LoadingCallback
import cn.holy.app.xcddt.repository.UserRepository
import javax.inject.Inject


/**
 * Created by xionghao on 2018/2/23.
 */

class LoginViewModel @Inject // UserRepository parameter is provided by Dagger 2
constructor(private val userRepo: UserRepository) : ViewModel() {
    var user: UserBean? = null
        private set

    fun init() {
        if (this.user != null) {
            // ViewModel is created per Fragment so
            // we know the userId won't change
            return
        }
        user = userRepo.loadUser()
    }

    /**
     * 登录操作
     * @param username 账号
     * @param password 密码
     * @param checked 是否保存账号
     */
    fun login(username: String, password: String, checked: Boolean, callback: LoadingCallback<UserBean>) {

        if (checked) {
            userRepo.saveLoginInfo(username, password)
        }
//        callback.onSuccess(UserBean())


        userRepo.doLogin(username, password, object : LoadingCallback<UserBean> {
            override fun onSuccess() {
            }

            override fun onStart() {
                callback.onStart()
            }

            override fun onError(msg: String) {
                callback.onError(msg)
            }

            override fun onSuccess(userInfoBean: UserBean) {
                callback.onSuccess(userInfoBean)
            }

            override fun onCompleted() {
                callback.onCompleted()
            }
        })
    }


    fun loadLoginInfo(): LoginFormBean {
        return userRepo.loadLoginInfo()
    }

}
